<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>订票管理系统</title>
    <meta name="keywords" content="Bootstrap模版,Bootstrap模版下载,Bootstrap教程,Bootstrap中文"/>
    <meta name="description" content="站长素材提供Bootstrap模版,Bootstrap教程,Bootstrap中文翻译等相关Bootstrap插件下载"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <!-- basic styles -->

    <link href="/static/css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="/static/css/bootstrapValidator.min.css"/>
    <link rel="stylesheet" href="/static/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="/static/css/ace.min.css"/>
    <link rel="stylesheet" href="/static/css/ace-rtl.min.css"/>
    <link rel="stylesheet" href="/static/css/ace-skins.min.css"/>
    <link rel="stylesheet" href="/static/js/select2/select2.css"/>

    <script src="/static/js/jquery-3.4.1.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/js/typeahead-bs2.min.js"></script>
    <script src="/static/js/jquery.form.min.js"></script>
    <script src="/static/js/jquery.dataTables.min.js"></script>
    <script src="/static/js/dataTables.bootstrap.min.js"></script>
    <script src="/static/js/jquery.dataTables.bootstrap.js"></script>
    <script src="/static/js/bootstrapValidator.min.js"></script>
    <script src="/static/js/language/zh_CN.js"></script>
    <script src="/static/js/dataTablesi-i18n-zh_cn.js"></script>
    <script src="/static/js/select2/select2.min.js"></script>

    <script type="text/javascript">
        $(function () {
            //渲染表格
            let mytable = $('#mytab').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": {
                    url: '/reservation/query',
                    //查询条件
                    data: {
                        "identity": "",
                        "name": "",
                        "gender": ""
                    }
                },
                "language": i18n_cn,//汉化
                "lengthMenu": [3, 5, 10],//每页多少条
                "sDom": '<"top">rt<"bottom"lp><"clear">',//表格控件布局
                //[]左右空格防止跟tm表达式冲突
                "order": [1, 'asc'],
                "columnDefs": [
                    {
                        targets: [0],
                        data: null,
                        orderable: false,
                        render: function (data, type, row, meta) {
                            return '<input type="checkbox" name="id" value="' + row.id + '">';
                        }
                    },
                    {
                        targets: [1],
                        data: 'identity',
                        orderable: true
                    },
                    {
                        targets: [2],
                        data: 'name',
                        orderable: true
                    },
                    {
                        targets: [3],
                        orderable: true,
                        data: function (row, type, set) {
                            console.log(row.gender)
                            if (row.gender == 0)
                                return '女';

                            else if (row.gender == 1)
                                return '男';
                            else return '';
                        }
                    },
                    {
                        targets: [4],
                        data: function (row, type, set) {
                            if (row.departureTime == null)
                                return "";
                            else return formatDate(row.departureTime);
                        },
                        orderable: true,
                    },
                    {
                        targets: [5],
                        data: function (row, type, set) {
                            if (row.toCity == null)
                                return "";
                            else return row.toCity;
                        },
                        orderable: true,
                    },
                    {
                        targets: [6],
                        data: 'fno',
                        orderable: true
                    },
                    {
                        targets: [7],
                        data: function (row, type, set) {
                            if (row.price == null)
                                return "";
                            else return row.price;
                        },
                        orderable: true,
                    },
                    {
                        className: 'queryreservation',//必须加一个样式
                        targets: [8],
                        data: null,
                        orderable: false,
                        render: function (data, type, row, meta) {
                            return '<a href="#">打印机票</a>';
                        }
                    }
                ],
            });

            // //用select2插件生成班主任下拉框
            // $.ajax({
            //     url: "/teacher/ajax4select2",
            //     dataType: 'json',
            //     cache: false,
            //     success: function (data) {
            //         $('#tid').select2({
            //             data: data,
            //             language: "zh-CN",//汉化
            //         });
            //     }
            // });

            //点击新增按钮
            $("#addBtn").click(function () {
                $("#myModalLabel").html("新增");
                //弹出表单模态窗口
                $('#myModal').modal('show');
            })

            function formatDate(d) {
                // 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
                var datetime =  new Date(d)
                var year = datetime.getFullYear(),
                    month = ("0" + (datetime.getMonth() + 1)).slice(-2),
                    date = ("0" + datetime.getDate()).slice(-2),
                    hour = ("0" + datetime.getHours()).slice(-2),
                    minute = ("0" + datetime.getMinutes()).slice(-2),
                    second = ("0" + datetime.getSeconds()).slice(-2);
                // 拼接
                var result = year + "-"+ month +"-"+ date +" "+ hour +":"+ minute +":" + second;
                // 返回
                return result;
            }

            //点击修改按钮
            $("#modBtn").click(function () {
                // alert("请把该功能写完")
                //判断有没有选中一位旅客
                var $checked = $("#mytab :checkbox[name=id]:checked");
                if ($checked.length != 1) {
                    alert("必须且最多选择一位旅客");
                    return;
                }
                //获取被选中的复选框s所在的行
                let tr = $checked.closest('tr');

                let row = mytable.row(tr);
                //当前行的数据对象
                let r = row.data();
                //表单赋值
                $("#id").val(r.id);
                $("#identity").val(r.identity);
                $("#name").val(r.name);
                $(":radio[name=gender]").each(function () {
                    if ($(this).val() == s.gender) {
                        $(this).prop("checked", "checked");
                    }
                });
                $("#departureTime").val(r.departureTime);
                $("#toCity").val(r.toCity);
                $("#fno").val(r.fno);
                $("#price").val(r.price);

                $("#myModalLabel").html("修改");
                //弹出表单模态窗口
                $('#myModal').modal('show');
            })

            //复选框全选
            $("#checkall").click(function () {
                $("#mytab tbody :checkbox").prop("checked", $(this).prop("checked"));
            })

            //点击删除按钮
            $("#delBtn").click(function () {
                //判断有没有选中一个用户
                let $checked = $("#mytab :checkbox[name=id]:checked");
                if ($checked.length < 1) {
                    alert("必须至少选择一个用户");
                    return;
                }
                let ids = $checked.map(function (index, item) {
                    return $(item).val();
                }).get();
                console.log(ids);
                if (confirm("确定要删除此订单吗?")) {
                    $.ajax({
                        url: "/reservation/delsome",
                        type: "DELETE",
                        data: JSON.stringify(identity),
                        contentType: "application/json",
                        dataType: 'json',
                        cache: false,
                        async: true,
                        statusCode: statusCode,
                        success: function (jsonResult) {
                            if ("0" == jsonResult.code) {
                                alert(jsonResult.msg);
                            }
                        }

                    })
                }
            })


            //点击查询按钮
            $("#queryBtn").click(function () {
                var identity = $("#identityconn").val();
                var name = $("#nameconn").val();
                var gender;
                if(document.getElementById("genderconn").checked){
                    gender = 0;
                }else{
                    gender = 1;
                }
                if (mytable) {
                    var param = {
                        "identity": identity,
                        "name": name,
                        "gender": gender
                    };
                    // console.log(param)
                    //封装参数
                    mytable.settings()[0].ajax.data = param;
                    //重新加载表格
                    mytable.ajax.reload();
                }
            });

            let statusCode = {
                500: function (response) {
                    alert("系统内部异常，请稍后再试")
                },
                400: function (response) {
                    alert("表单参数不合法!")
                    $("#formerrorinfo").html(response.responseJSON.msg)
                },
                403: function (response) {
                    alert("您无权操作该资源!")
                }
            }

            //查询该旅客的订票信息并渲染
            function format(data) {
                let childTab = '';
                $.ajax({
                    url: '/reservation/' + data.id,
                    dataType: 'json',
                    async: false,//同步的方式
                    statusCode: statusCode,
                    //请求处理成功,相当于返回码200系列
                    success: function (jsonResult) {
                        console.log(jsonResult.data)
                        if (jsonResult.data[0] == null) {
                            childTab += "没有该旅客的订票信息";
                        } else {
                            childTab += '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
                            childTab += "<tr style='color:#4682B4'><td>身份证号码</td><td>姓名</td><td>性别</td>" +
                                "                <td>航班日期</td><td>航班目的地</td><td>班次</td><td>票价</td></tr>";
                            $.each(jsonResult.data, function (i, e) {
                                childTab += "<tr>";
                                childTab += "<td>" + e.customer.identity + "</td>";
                                childTab += "<td>" + e.customer.name + "</td>";
                                childTab += "<td>" + e.customer.gender + "</td>";
                                childTab += "<td>" + e.flightInfo.departureTime + "</td>";
                                childTab += "<td>" + e.route.toCity + "</td>";
                                childTab += "<td>" + e.distribution.price + "</td>";
                                childTab += "</tr>";
                            });
                            childTab += "</table>";
                        }

                    }
                });
                return childTab;
            }

            //点击【查看订单】
            $('#mytab tbody').on('click', 'td.queryResveration', function () {
                //获取【查看订单】按钮所在的行
                let tr = $(this).closest('tr');
                let row = mytable.row(tr);
                if (row.child.isShown()) {
                    //隐藏
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    let tab = format(row.data());
                    //如果有内容，就展开表格
                    if (tab != '') {
                        //展开
                        row.child(tab).show();
                        tr.addClass('shown');
                    }
                }
            });

            //点击表单的提交按钮
            $('#submitBtn').click(function () {

                //提交的JSON格式数据
                let formParamJson = {
                    "id": $('#id').val(),
                    "identity": $('#identity').val(),
                    "name": $('#name').val(),
                    "gender": $(':radio[name=gender]:checked').val(),
                    "departureTime": $('#departureTime').val(),
                    "toCity": $('#toCity').val(),
                    "fno": $('#fno').val(),
                    "price": $('#price').val(),
                    "rno": $('#rno').val(),
                    "cno": $('#cno').val()
                }

                 console.log('formParamJson='+JSON.stringify(formParamJson));
                function restfulSubmit(url, requestMethod) {
                    //提交表单 REST风格
                    $.ajax({
                        url: url ,
                        type: requestMethod,
                        data: JSON.stringify(formParamJson),
                        contentType: "application/json;charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        async: false,//同步的方式
                        statusCode: statusCode,
                        success: function (jsonResult) {
                            alert("操作成功!");
                            //重置form
                            $("#modelForm")[0].reset();
                            // $("#tid").select2("val", [""]);
                        }
                    });
                }

                if ($("#myModalLabel").html() == "新增") {
                    restfulSubmit("/reservation/add", "POST");
                } else if ($("#myModalLabel").html() == "修改") {
                    restfulSubmit("/reservation/" + $('#id').val(), "PUT");
                }
            });

            //myModal关闭时重置表单
            $('#myModal').on('hidden.bs.modal', function () {
                $("#modelForm")[0].reset();
                // $("#tid").select2("val", [""]);
                //清空表单校验错误提示信息
                $("#formerrorinfo").html("");
                mytable.ajax.reload();
            });
        });
    </script>
</head>
<body>
<div class="breadcrumbs" id="breadcrumbs">
    <script type="text/javascript">
        try {
            ace.settings.check('breadcrumbs', 'fixed')
        } catch (e) {
        }
    </script>
    <ul class="breadcrumb">
        <li>
            <i class="icon-home home-icon"></i>
            <a href="#">后台管理</a>
        </li>

        <li>
            <a href="#">订票管理</a>
        </li>
    </ul>
    <div class="row">
        <div class="col-xs-12">
            <div class="result-title">
                <div>
                    <button id="addBtn" class="btn btn-xs btn-primary" type="button">
                        <i class="icon-plus bigger-120"> 新增</i>
                    </button>
                    <button id="modBtn" class="btn btn-xs btn-warning" type="button">
                        <i class="icon-wrench bigger-120"> 修改</i>
                    </button>
                    <button id="delBtn" class="btn  btn-xs btn-danger" type="button">
                        <i class="icon-trash bigger-120"> 删除</i></button>
                    身份证号:<input type="text" id="identityconn">
                    姓名:<input type="text" id="nameconn">
                    性别: <input type="radio" name="gender" value="0" checked id="genderconn" >女
                    <input type="radio" name="gender" value="1" >男
                </select>
                    <button class="btn btn-xs btn-primary" id="queryBtn" type="button">
                        <i class="icon-search bigger-120"> 查询</i>
                    </button>
                </div>
            </div>
            <div class="table-header">
                订票信息表
            </div>

            <div class="table-responsive">
                <form action="" method="post" id="delForm">
                    <table id="mytab" class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>
                                <div class="center">
                                    <label>
                                        <input type="checkbox" id="checkall" class="ace"/>
                                        <span class="lbl"></span>
                                    </label>
                                </div>
                            </th>
                            <th>身份证号</th>
                            <th>姓名</th>
                            <th>性别</th>
                            <th>航班日期</th>
                            <th>航班目的地</th>
                            <th>班次</th>
                            <th>价格</th>
                            <th>操作</th>
                        </tr>
                        </thead>

                        <tbody>
                        </tbody>
                    </table>
                </form>
            </div>
        </div>
    </div>
</div><!-- /.col -->
<div id="infodiv">
</div>
<div class="modal fade" id="myModal" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">新增</h4>
            </div>
            <!--该表单使用Ajax方式提交 -->
            <form id="modelForm" class="form-horizontal" enctype="multipart/form-data" method="post">
                <div class="modal-body">
                    <input id="id" type="hidden" name="id" value="">
                    <div class="form-group">
                        <label for="identity" class="text-right"> 身份证号: </label>
                        <input id="identity" type="text" name="identity" class="form-control"
                               required="required" placeholder="必填"/>
                    </div>
                    <div class="form-group">
                        <label for="name" class="text-right">姓名: </label>
                        <input id="name" type="text" class="form-control" name="name"
                               placeholder="必填" required>
                    </div>
                    <div class="form-group">
                        <label class="text-right">性别: </label>
                        <input type="radio" name="gender" value="0" checked>女
                        <input type="radio" name="gender" value="1">男
                    </div>
                    <div class="form-group">
                        <label for="departureTime" class="text-right">航班日期: </label>
                        <input id="departureTime" type="date" class="form-control" name="departureTime"
                               placeholder="必填" required>
                    </div>
                    <div class="form-group">
                        <label for="toCity" class="text-right">航班目的地: </label>
                        <input id="toCity" type="text" class="form-control" name="toCity">
                    </div>
                    <div class="form-group">
                        <label for="fno" class="text-right">班次: </label>
                        <input id="fno" type="text" class="form-control" name="fno">
                    </div>
                    <div class="form-group">
                        <label for="rno" class="text-right">航线编号: </label>
                        <input id="rno" type="text" class="form-control" name="rno">
                    </div>
                    <div class="form-group">
                        <label for="cno" class="text-right">舱位等级编号: </label>
                        <input id="cno" type="text" class="form-control" name="cno">
                    </div>
                    <div class="form-group">
                        <label for="price" class="text-right">价格: </label>
                        <input id="price" type="text" class="form-control" name="price">
                    </div>

                    <div id="formerrorinfo" class="form-group" style="color:#ff0000">

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="submitBtn" type="button" class="btn btn-primary">提交</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>